package com.longmen.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.longmen.constant.MessageConstant;
import com.longmen.exception.NotDeleteException;
import com.longmen.mapper.ItemCategoryMapper;
import com.longmen.pojo.dto.ItemCategoryDto;
import com.longmen.pojo.dto.PageQueryDto;
import com.longmen.pojo.entity.ItemCategory;
import com.longmen.result.PageResult;
import com.longmen.service.ItemCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ItemCategoryServiceImpl implements ItemCategoryService {

    @Autowired
    private ItemCategoryMapper itemCategoryMapper;

    /**
     * 分类查询类目列表
     *
     * @return
     */
    public PageResult PageList(PageQueryDto pageQueryDto) {
        PageHelper.startPage(pageQueryDto.getPage(), pageQueryDto.getPageSize());
        //如果是顶级节点就显示出来
        Page<ItemCategory> page = itemCategoryMapper.selectByParentId();

        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 根据id查询子节点
     */
    public List<ItemCategoryDto> queryTreeNodes(Integer id) {
        List<ItemCategoryDto> list = itemCategoryMapper.selectTreeNodes(id);
        //将list转map,以备使用
        Map<Integer, ItemCategoryDto> mapTemp = list.stream()
                .collect(Collectors
                        .toMap(key -> key.getXxxLbid(), value -> value, (key1, key2) -> key2));
        //最终返回的list
        List<ItemCategoryDto> categoryTreeDtos = new ArrayList<>();
        //依次遍历每个元素,排除根节点
        list.stream().filter(item -> !id.equals(item.getXxxLbid())).forEach(item -> {
            if (item.getXxxPid().equals(id)) {
                categoryTreeDtos.add(item);
            }
            //找到当前节点的父节点
            ItemCategoryDto itemCategoryDto = mapTemp.get(item.getXxxPid());
            if (itemCategoryDto != null) {
                if (itemCategoryDto.getChildrenTreeNodes() == null) {
                    itemCategoryDto.setChildrenTreeNodes(new ArrayList<ItemCategoryDto>());
                }
                //下边开始往ChildrenTreeNodes属性中放子节点
                itemCategoryDto.getChildrenTreeNodes().add(item);
            }
        });
        return categoryTreeDtos;
    }

    /**
     * 添加分类
     * @param itemCategory
     */
    public void insertCategory(ItemCategory itemCategory) {
        itemCategoryMapper.insertCategory(itemCategory);
    }

    /**
     * 删除分类
     * @param id
     */
    public void deleteById(Integer id) {
        List<ItemCategory> itemCategorys = itemCategoryMapper.getByParentId(id);
        if (itemCategorys != null && itemCategorys.size() > 0){
            //说明有子节点不能删除
            throw new NotDeleteException(MessageConstant.NOTDELETE_ERROR);
        }
        itemCategoryMapper.deleteById(id);
    }
}
